/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.service.impl;

import me.zhengjie.domain.Reader;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.ReaderRepository;
import me.zhengjie.service.ReaderService;
import me.zhengjie.service.dto.ReaderDto;
import me.zhengjie.service.dto.ReaderQueryCriteria;
import me.zhengjie.service.mapstruct.ReaderMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author ...
* @date 2020-11-08
**/
@Service
@RequiredArgsConstructor
public class ReaderServiceImpl implements ReaderService {

    private final ReaderRepository readerRepository;
    private final ReaderMapper readerMapper;

    @Override
    public Map<String,Object> queryAll(ReaderQueryCriteria criteria, Pageable pageable){
        Page<Reader> page = readerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(readerMapper::toDto));
    }

    @Override
    public List<ReaderDto> queryAll(ReaderQueryCriteria criteria){
        return readerMapper.toDto(readerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReaderDto findById(Integer readerId) {
        Reader reader = readerRepository.findById(readerId).orElseGet(Reader::new);
        ValidationUtil.isNull(reader.getReaderId(),"Reader","readerId",readerId);
        return readerMapper.toDto(reader);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReaderDto create(Reader resources) {
        if(readerRepository.findByNickname(resources.getNickname()) != null){
            throw new EntityExistException(Reader.class,"nickname",resources.getNickname());
        }
        if(readerRepository.findByIdentityCard(resources.getIdentityCard()) != null){
            throw new EntityExistException(Reader.class,"identity_card",resources.getIdentityCard());
        }
        if(readerRepository.findByPhoneNum(resources.getPhoneNum()) != null){
            throw new EntityExistException(Reader.class,"phone_num",resources.getPhoneNum());
        }
        if(readerRepository.findByEmail(resources.getEmail()) != null){
            throw new EntityExistException(Reader.class,"email",resources.getEmail());
        }
        if(readerRepository.findByQqId(resources.getQqId()) != null){
            throw new EntityExistException(Reader.class,"qq_id",resources.getQqId());
        }
        if(readerRepository.findByWxId(resources.getWxId()) != null){
            throw new EntityExistException(Reader.class,"wx_id",resources.getWxId());
        }
        if(readerRepository.findByOpenId(resources.getOpenId()) != null){
            throw new EntityExistException(Reader.class,"open_id",resources.getOpenId());
        }
        return readerMapper.toDto(readerRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Reader resources) {
        Reader reader = readerRepository.findById(resources.getReaderId()).orElseGet(Reader::new);
        ValidationUtil.isNull( reader.getReaderId(),"Reader","id",resources.getReaderId());
        Reader reader1 = readerRepository.findByNickname(resources.getNickname());
        if(reader1 != null && !reader1.getReaderId().equals(reader.getReaderId())){
            throw new EntityExistException(Reader.class,"nickname",resources.getNickname());
        }
        reader1 = readerRepository.findByIdentityCard(resources.getIdentityCard());
        if(reader1 != null && !reader1.getReaderId().equals(reader.getReaderId())){
            throw new EntityExistException(Reader.class,"identity_card",resources.getIdentityCard());
        }
        reader1 = readerRepository.findByPhoneNum(resources.getPhoneNum());
        if(reader1 != null && !reader1.getReaderId().equals(reader.getReaderId())){
            throw new EntityExistException(Reader.class,"phone_num",resources.getPhoneNum());
        }
        reader1 = readerRepository.findByEmail(resources.getEmail());
        if(reader1 != null && !reader1.getReaderId().equals(reader.getReaderId())){
            throw new EntityExistException(Reader.class,"email",resources.getEmail());
        }
        reader1 = readerRepository.findByQqId(resources.getQqId());
        if(reader1 != null && !reader1.getReaderId().equals(reader.getReaderId())){
            throw new EntityExistException(Reader.class,"qq_id",resources.getQqId());
        }
        reader1 = readerRepository.findByWxId(resources.getWxId());
        if(reader1 != null && !reader1.getReaderId().equals(reader.getReaderId())){
            throw new EntityExistException(Reader.class,"wx_id",resources.getWxId());
        }
        reader1 = readerRepository.findByOpenId(resources.getOpenId());
        if(reader1 != null && !reader1.getReaderId().equals(reader.getReaderId())){
            throw new EntityExistException(Reader.class,"open_id",resources.getOpenId());
        }
        reader.copy(resources);
        readerRepository.save(reader);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer readerId : ids) {
            readerRepository.deleteById(readerId);
        }
    }

    @Override
    public void download(List<ReaderDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ReaderDto reader : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户姓名 ", reader.getReaderName());
            map.put("昵称 唯一 ", reader.getNickname());
            map.put("密码 md5加密 ", reader.getPassword());
            map.put("头像地址 ", reader.getAvatar());
            map.put("身份证号 唯一 ", reader.getIdentityCard());
            map.put("电话号码 唯一 ", reader.getPhoneNum());
            map.put("邮箱 ", reader.getEmail());
            map.put("职业 ", reader.getOccupation());
            map.put("职称 ", reader.getProfessional());
            map.put("学历 ", reader.getEducation());
            map.put("读者等级 对应r_rank表 ", reader.getLevel());
            map.put("签名 ", reader.getSignature());
            map.put(" qqId",  reader.getQqId());
            map.put(" wxId",  reader.getWxId());
            map.put(" openId",  reader.getOpenId());
            map.put("是否被封号,1被封号,0解封 ", reader.getIsBaned());
            map.put("物流偏好 快递公司编码 ", reader.getShippercode());
            map.put("生日", reader.getBirthday());
            map.put("0:男 1:女 默认0 ", reader.getSex());
            map.put("是否隐藏手机号码,1被隐藏,0不隐藏 ", reader.getPhoneIsHid());
            map.put("是否启用 1启用 0未启用", reader.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}